package cfca.paperless.client.servlet._9_unite;

import java.io.File;
import java.io.FileInputStream;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.FieldBean;
import cfca.paperless.client.bean.ImageBean;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.bean.TextBean;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.Base64;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import cfca.sadk.x509.certificate.X509Cert;

/**
 * @Description 联合接口(合成业务模板,自助生成图片,自动化计算pdf签章hash值)
 * @author zf
 * @CodeReviewer ts
 */
public class PaperlessUniteTest05 {

    public static void main(String[] args) throws Exception {
        PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.url, 10000, 60000);
        PaperlessClient clientBean4Assist = new PaperlessClient(PaperlessConfig.assistUrl, 10000, 60000);// 无纸化辅助接口的访问URL
        PaperlessClient clientBean4Ext = new PaperlessClient(PaperlessConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL
        long timeStart = System.currentTimeMillis();// 开始时间

        // PaperlessUniteClient clientBean = new
        // PaperlessUniteClient(PaperlessConfig.uniteUrl);

        boolean flag = false;
        byte[] imageResult = "".getBytes();

        // 操作员编码或者机构号
        String operatorCode = PaperlessConfig.operatorCode;
        // 渠道编码，可以为空
        String channelCode = PaperlessConfig.channelCode;

        // ////////////////////////////////合成模板(synthesizeAutoTemplate)///////////////////////////////////
        String templateCode = "tmp005";
        String fieldBeanListXml = PaperlessUtil.buildFieldBeanListXml(getFieldBeanList());
        String textBeanListXml = PaperlessUtil.buildTextBeanListXml(getTextBeanList());
        String imageBeanListXml = PaperlessUtil.buildImageBeanListXml(getImageBeanList());
        // clientBean.addSynthesizeAutoTemplateParams(templateCode,
        // fieldBeanListXml, textBeanListXml, imageBeanListXml);
 
        byte[] pdf = clientBean.synthesizeAutoTemplate(templateCode, fieldBeanListXml, textBeanListXml, imageBeanListXml, operatorCode, channelCode);
        String errorRsString = PaperlessUtil.isError(pdf);
        if ("".equals(errorRsString)) {
            System.out.println("OK:synthesizeAutoTemplate");
            IoUtil.write("./TestData/output/synthesizeAutoTemplate.pdf", pdf);
            // ////////////////////////////////自助生成图片(autoGenerateImage)//////////////////////////////////////
            imageResult = doAutoGenerateImage(clientBean4Assist);

            errorRsString = PaperlessUtil.isError(imageResult);

            if ("".equals(errorRsString)) {
                System.out.println("OK:autoGenerateImage");
                System.out.println(imageResult.length);
                IoUtil.write("./TestData/output/autoGenerateImage22.png", imageResult);
                flag = true;
            } else {
                // 处理结果为异常，打印出错误码和错误信息
                System.out.println("NG:autoGenerateImage");
                System.out.println(imageResult.length);
                System.out.println(errorRsString);
               
            }

        } else {
            System.out.println(new String(pdf, "UTF-8"));
        }

        if (flag) {
            
            //////////////////////////////////自动化计算PDF签章HASH值(autoCalculatePdfHash)////////////////////////

            byte[] x509Cert = FileUtils.readFileToByteArray(new File("./TestData/cert/tl1024.cer"));
            X509Cert cert = new X509Cert(x509Cert);

            String sealReason = "业务";
            String sealLocation = "china";
            String hashAlg = "sha1";
            // 签章位置
            byte[] sealImage = imageResult;
            SignLocation signLocation = new SignLocation(1, 20, 15);// 坐标签章
            String strategyXml = StrategyUtil.createClientSealStrategyXml(sealReason, sealLocation,sealImage, signLocation, hashAlg);

            String returnMessage = clientBean4Ext.autoCalculatePdfHash("",pdf, cert.getEncoded(), strategyXml, operatorCode, channelCode);
            String code = StringUtil.getNodeText(returnMessage, "Code");
            if ("200".equals(code)) {
                System.out.println("OK:autoCalculatePdfHash");
                String pdfSealHash = StringUtil.getNodeText(returnMessage, "PdfSealHash");// pdf签名hash的base64值
                String pdfSealSource = StringUtil.getNodeText(returnMessage, "PdfSealSource");// pdf签名原文的base64值
                String id = StringUtil.getNodeText(returnMessage, "Id");// 标识,用来对应后台的缓存数据
                System.out.println("返回的PDF文档HASH值：" + pdfSealHash);
                System.out.println("返回的PDF文档原文：" + pdfSealSource);
                System.out.println("返回的ID：" + id);
                 
                //私钥
                PrivateKey privateKey = KeyUtil.getPrivateKeyFromPFX(new FileInputStream("./TestData/cert/tl1024.pfx"), "11111111");
                JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, null);
                cfca.sadk.lib.crypto.Session mySession = JCrypto.getInstance().openSession(JCrypto.JSOFT_LIB);
                Signature sigUtil = new Signature();
                byte[] signature = null;
                System.out.println("pdfSealHash:" + new String(pdfSealHash));
                //对hash进行签名
                signature = sigUtil.p7SignByHash(Mechanism.SHA1_RSA, Base64.decode(pdfSealHash), privateKey, new X509Cert(x509Cert), mySession);
                System.out.println("signature:" + new String(signature)); 
                
                
            }else{
                System.out.println("获得PDF文档HASH值失败！" + returnMessage);
            }

        }

        long timeEnd = System.currentTimeMillis();// 结束时间
        System.out.println("time:" + (timeEnd - timeStart));
    }

    private static List<FieldBean> getFieldBeanList() throws Exception {
        List<FieldBean> fieldBeanList = new ArrayList<FieldBean>();
        String address = "11的快捷付款捷付款的机发及啊啊啊啊啊啊啊啊啊啊";
        fieldBeanList.add(new FieldBean("operator", "会计法", "", "text"));
        fieldBeanList.add(new FieldBean("date", "2011年11月11", "", "text", 2));
        fieldBeanList.add(new FieldBean("branch", "ddddddddddddd", "", "text", 2));
        fieldBeanList.add(new FieldBean("fingerCode", "Sucaili", "", "text", 2));
        fieldBeanList.add(new FieldBean("signature1", "Sucaili", "", "text", 1));
        fieldBeanList.add(new FieldBean("identNo", "Sucaili", "", "text", 1));
        fieldBeanList.add(new FieldBean("identType", "Sucaili", "", "text"));
        fieldBeanList.add(new FieldBean("ICcardType", "Sucaili", "", "text", 1));
        fieldBeanList.add(new FieldBean("accountName", "张凡的", "", "text", 1));
        fieldBeanList.add(new FieldBean("cardNo1", "Sucaili", "", "text", 1));
        fieldBeanList.add(new FieldBean("sequenceNo1", "Sucaili", "", "text", 1));
        fieldBeanList.add(new FieldBean("address", address, "", "text", 3));
        fieldBeanList.add(new FieldBean("B1", "Sucaili", "", "text", 1));

        return fieldBeanList;
    }

    private static List<TextBean> getTextBeanList() throws Exception {
        List<TextBean> textBeanList = new ArrayList<TextBean>();
        TextBean textBean1 = new TextBean("你好啊\r\n我的啊\r\ndddddd", "", "银行签章：", "R", 0, 0);
        textBean1.setTextFontSize("15");
        textBean1.setTextColor("aa000000");
        TextBean textBean2 = new TextBean("545454545452212323\r\ndddddddddddddddddddddddd\r\n打开房间打开附件\r\ndkjfdkjf你的额尔", "", "单据号：", "R", 0, 0);
        // textBean2.setSpacingHeight(20);//设置行间距默认15像素
        textBean2.setTextFontSize("15");
        textBean2.setTextColor("aa000000");
        textBeanList.add(textBean1);
        textBeanList.add(textBean2);

        return textBeanList;
    }

    private static List<ImageBean> getImageBeanList() throws Exception {
        List<ImageBean> imageBeanList = new ArrayList<ImageBean>();
        // 如下代码是在pdf中添加可以显示的图片
        byte[] imageData = FileUtils.readFileToByteArray(new File("./TestData/1.png"));
        ImageBean imageBean0 = new ImageBean("100", "100", "签章", "C", 0, 0, imageData, 1);
        
        String imagePath = Base64.toBase64String("D:/TestData/1.png".getBytes("utf-8"));
        
        ImageBean imageBean = new ImageBean("100", "100", 1, "400", "300", imagePath, 2);
        
        imageBean.setImagePath(imagePath);
        imageBeanList.add(imageBean0);
        imageBeanList.add(imageBean);
        
        return imageBeanList;
    }

    /**
     * 生成图片生成策略文件
     * 
     * @return
     */
    public static String createImageStrategyXml(String name, String name2, String name2Style, int width, int height, int shape, String color, int fontSize,
            String businessCode, String businessCodeStyle) {

        StringBuilder imageStrategyXML = new StringBuilder();

        imageStrategyXML.append("<Request>");
        imageStrategyXML.append("<ImageName>").append(name).append("</ImageName>");// 长方形换行字符“##”
        imageStrategyXML.append("<ImageName2>").append(name2).append("</ImageName2>");//
        imageStrategyXML.append("<ImageWidth>").append(width).append("</ImageWidth>");// 图片宽
        imageStrategyXML.append("<ImageHeight>").append(height).append("</ImageHeight>");// 图片高
        imageStrategyXML.append("<ImageShape>").append(shape).append("</ImageShape>");
        // 1：方型 11：方形（带框） 2：长方形（不带“章”字） 21：长方形（带框） 3：圆形（不带五角星） 4：圆形（带五角星）
        imageStrategyXML.append("<Color>").append(color).append("</Color>"); // 十六进制，默认FF0000
        imageStrategyXML.append("<FontSize>").append(fontSize).append("</FontSize>"); // 字体大小，默认100
        if (StringUtil.isNotEmpty(businessCode)) {
            imageStrategyXML.append("<BusinessCode>").append(businessCode).append("</BusinessCode>");
            imageStrategyXML.append("<BusinessCodeStyle>").append(businessCodeStyle).append("</BusinessCodeStyle>");
        }

        if (StringUtil.isNotEmpty(name2Style)) {
            imageStrategyXML.append("<ImageName2Style>").append(name2Style).append("</ImageName2Style>");
        }

        imageStrategyXML.append("</Request>");

        return imageStrategyXML.toString();
    }

    /**
     * 
     * @Description: 自助生成图片
     * @return: void
     * @throws Exception
     */
    private static byte[] doAutoGenerateImage(PaperlessClient clientBean4Assist) throws Exception {
        String businessCode = "ABC123456789";
        String businessCodeStyle = "";// "font-family:宋体,font-size:20;x-ratio:0.5;y-ratio:0.6";
        String name = "印章名称";
        String name2 = "测试用章123";
        String name2Style = "font-family:仿宋;font-size:60;x-ratio:0.5;y-ratio:1";
        int width = 600;
        int height = 600;
        int shape = 4; // 1：方型11：方形（带框）2：长方形（不带“章”字）21：长方形（带框）3：圆形（不带五角星）4：圆形（带五角星）
        String color = "FF0000";
        int fontSize = 100;
        String imageStrategyXml = createImageStrategyXml(name, name2, name2Style, width, height, shape, color, fontSize, businessCode, businessCodeStyle);

        // clientBean.addAutoGenerateImageParams(imageStrategyXml);
        String systemNo = GUID.generateId();//业务流水号 
       
        byte[] result = clientBean4Assist.autoGenerateImage(systemNo,imageStrategyXml, PaperlessConfig.operatorCode, PaperlessConfig.channelCode);

        return result;
    }

}
